using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace SBPweb.Presentation.Windows.Forms.Host.Controls
{
	public partial class ErrorForm : SBPweb.Controls.Windows.Common.Form
	{
		private Exception ex;

		public ErrorForm()
		{
			InitializeComponent();

            if (Program.IsInExplorerMode)
            {
                sbClose.Enabled = false;
            }
		}

		public ErrorForm(Exception ex)
		{
			InitializeComponent();

            if (Program.IsInExplorerMode)
            {
                sbClose.Enabled = false;
            }

			Exception = ex;
		}

		public Exception Exception
		{
			get
			{
				return ex;
			}
			set
			{
				ex = value;
				//lMessage.Text = ex.Message;

				//Graphics graphics = lMessage.CreateGraphics();
				Graphics graphics = tbMessage.CreateGraphics();
				SizeF textSize = graphics.MeasureString(ex.Message, tbMessage.Font, this.Width);
				float wText = textSize.Width;
				float hText = textSize.Height;
				//int i = (int)((int)(wText / lMessage.Width) + 1);
				//lMessage.MinimumSize = new Size((int)wText, (int)hText);

				//lMessage.Text = ex.Message;
				tbMessage.MinimumSize = new Size((int)wText, (int)hText);

				TextChange(ex.Message, ex.StackTrace);
			}
		}

		private delegate void TextChangeHandler(string message, string trace);

		private void TextChange(string message, string trace)
		{
			if (tbMessage.InvokeRequired)
			{
				tbMessage.Invoke(new TextChangeHandler(TextChange), message, trace);
				return;
			}
			tbMessage.Text = message;
			meTrace.Text = trace;
		}

		void tbMessage_GotFocus(object sender, EventArgs e)
		{
			tbMessage.ReadOnly = true;
		}

		void tbMessage_LostFocus(object sender, System.EventArgs e)
		{
			tbMessage.ReadOnly = false;
		}

		private void sbRestart_Click(object sender, EventArgs e)
		{
			Application.Restart();
			Application.ExitThread();
		}

		private void sbClose_Click(object sender, EventArgs e)
		{
			Application.ExitThread();
		}

		private void meTrace_MouseDown(object sender, MouseEventArgs e)
		{
			switch (e.Button)
			{
				case MouseButtons.Right:
					System.Windows.Forms.Clipboard.SetText("Message: " + tbMessage.Text + "\r\nStack-trace: " + meTrace.Text);
					break;
			}
		}
	}
}